# coding=utf-8
# 代码文件：client/ui/login_frame.py

"""用户登录窗口"""
import sys
import wx
import os
import json
from ui.my_frame import MyFrame
from ui.file_list_frame import FileListFrame
from services.auth_service import AuthService


class LoginFrame(MyFrame):
    def __init__(self):
        super().__init__(title='用户登录', size=(340, 230))

        # 检查并创建缓存文件
        cache_file = 'user_session.json'
        if not os.path.exists(cache_file):
            with open(cache_file, 'w') as f:
                json.dump({}, f)  # 初始化为空的 JSON 对象

        # 创建界面控件
        accountid_st = wx.StaticText(self.contentpanel, label='账号：')
        password_st = wx.StaticText(self.contentpanel, label='密码：')
        self.accountid_txt = wx.TextCtrl(self.contentpanel)
        self.password_txt = wx.TextCtrl(self.contentpanel, style=wx.TE_PASSWORD)

        # 创建 FlexGrid 布局 fgs 对象
        fgs = wx.FlexGridSizer(2, 2, 20, 20)
        fgs.AddMany([(accountid_st, 1, wx.ALIGN_CENTRE_VERTICAL | wx.ALIGN_RIGHT | wx.FIXED_MINSIZE),
                     (self.accountid_txt, 1, wx.CENTER | wx.EXPAND),
                     (password_st, 1, wx.ALIGN_CENTRE_VERTICAL | wx.ALIGN_RIGHT | wx.FIXED_MINSIZE),
                     (self.password_txt, 1, wx.CENTER | wx.EXPAND)])
        # 设置 FlexGrid 布局对象
        fgs.AddGrowableRow(0, 1)
        fgs.AddGrowableRow(1, 1)
        fgs.AddGrowableCol(0, 1)
        fgs.AddGrowableCol(1, 4)

        # 创建按钮对象
        okb_btn = wx.Button(parent=self.contentpanel, label='确定')
        self.Bind(wx.EVT_BUTTON, self.okb_btn_onclick, okb_btn)
        cancel_btn = wx.Button(parent=self.contentpanel, label='取消')
        self.Bind(wx.EVT_BUTTON, self.cancel_btn_onclick, cancel_btn)

        # 创建水平 Box 布局 hbox 对象
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(okb_btn, 1, wx.CENTER | wx.ALL | wx.EXPAND, border=10)
        hbox.Add(cancel_btn, 1, wx.CENTER | wx.ALL | wx.EXPAND, border=10)

        # 创建垂直 Box 布局，把 fgs 和 hbox 添加到垂直 Box 布局对象上
        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(fgs, -1, wx.CENTER | wx.ALL | wx.EXPAND, border=25)
        vbox.Add(hbox, -1, wx.CENTER | wx.BOTTOM, border=20)

        self.contentpanel.SetSizer(vbox)

    def okb_btn_onclick(self, event):
        """确定按钮事件处理"""
        account_id = self.accountid_txt.GetValue()
        password = self.password_txt.GetValue()

        # 调用 AuthService 登录
        result = AuthService.login(account_id, password)

        if result and result.get('status') == 'success':
            print('登录成功。')
            # 保存会话数据
            AuthService.save_session({
                'short_jwt': result.get('short_jwt'),
                'long_jwt': result.get('long_jwt'),
                'user_data': result.get('user_data')
            })

            next_frame = FileListFrame()
            next_frame.Show()
            self.Hide()
        else:
            print('登录失败。')
            message = result.get('message', '登录失败，请重试。') if result else '服务器错误，请稍后重试。'
            dlg = wx.MessageDialog(self, message, '登录失败', wx.OK | wx.ICON_ERROR)
            dlg.ShowModal()
            dlg.Destroy()

    def cancel_btn_onclick(self, event):
        """取消按钮事件处理"""

        # 退出系统
        self.Destroy()
        sys.exit(0)
